<template>
	<view class="">
		<NavBar title="搜索" :isShowLeftBtn="true">
		</NavBar>
	</view>
	<view class="search_box ">
		<view class="nav_box m_b_20">
			<view class="m_b_14 m_r_8" style="flex-shrink: 0;">
				<up-image :show-loading="true" src="/static/images/index/index_position.png" width="20rpx"
					height="26rpx"></up-image>
				<!-- <up-icon name="/static/images/index/index_position.png" size="14"></up-icon> -->
			</view>
			<view class=" flex" @click="showCityPicker">
				<view class="m_r_8" style="max-width: 400rpx;">
					<text class="f_26_0 u-line-1">
						{{curAddress}}
					</text>
				</view>
				<view class="">
					<up-icon name="arrow-down-fill" size="14"></up-icon>
				</view>
			</view>

		</view>
		<view class="search_input m_b_30" :style="searchVal?{width:'710rpx'}:{paddingLeft:'46rpx',width:'666rpx'}">
			<view class="">
				<view class="search_icon" v-if="!searchVal">
					<up-icon name="search" color="#7E7D7D" size="18"></up-icon>
				</view>
				<view class="" style="">
					<up-input placeholder="请输入关键字" border="none" v-model="searchVal" inputAlign="center"
						fontSize="24rpx" @change="onSearchChage"></up-input>
				</view>
			</view>
		</view>
		<view class="row2_header">
			<view class="row2_header_list flex_both">
				<view :class="['row2_header_item',item.state.isSel?'row2_header_item_acitve':'']"
					v-for="(item,index) in row2HeaderList" :key="index" @click="onClickRow2HeaderItem(item)">
					<view class="m_r_32 m_b_6">
						<text class="text">
							{{item.label}}
						</text>
					</view>
					<view class="m_b_2">
						<view class="" v-if="item.state.status == 0">
							<up-icon name="arrow-up-fill" size="9" color="#C5C5C5"></up-icon>
							<up-icon name="arrow-down-fill" size="9" color="#C5C5C5"></up-icon>
						</view>
						<view class="active_box" v-else-if="item.state.status == 1">
							<view class="">
								<up-icon name="arrow-up" size="9" color="#F7480B"></up-icon>
							</view>
						</view>
						<view class="active_box" v-else-if="item.state.status == 2">
							<view class="m_t_2">
								<up-icon name="arrow-down" size="9" color="#F7480B"></up-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
	<view class="" style="height: 276rpx;background: #F7F8FC;">
	</view>
	<view class="content" :style="{height:contentHeight}">
		<view class="main">
			<scroll-view scroll-y="true" :style="{height: viewHeight }" :refresher-threshold="100"
				@scrolltolower="scrolltolowerFun" refresher-enabled="true" refresher-default-style="none">
				<view class="row2_list">
					<view class="row2_item m_b_20" v-for="(item,index) in storeList" :key="index"
						@click="toDetail(item)">
						<view class="row2_item_row1 flex_both" style="align-items: flex-start;">
							<view class="row2_item_row1_left flex_both m_b_30">
								<view class="m_r_28">
									<up-image :show-loading="true" :src="item.shop_images.split(',')[0]" width="160rpx"
										height="146rpx"></up-image>
								</view>
								<view class="" style="width: 480rpx;">
									<view class="flex_both" style="align-items: flex-start;">
										<view class="m_b_24" style="width: 300rpx;">
											<text class="f_30_0_b">
												{{item.shop_name}}
											</text>
										</view>
										<view class="row2_item_row1_right" style="transform: translateY(-6rpx);">
											<text class="f_24_9" style="color: #939393;">
												{{item.distance}}
											</text>
										</view>
									</view>
									<view class="">
										<view class="flex">
											<view class="m_r_12 m_b_6">
												<up-image :show-loading="true" src="/static/images/index/clock_icon.png"
													width="28rpx" height="28rpx"></up-image>
											</view>
											<view class="">
												<text class="f_24_0" style="color: #737272;">
													{{item.begin_hour}} - {{item.end_hour}}
												</text>
											</view>
											<view class="f_26_0 m_l_12 m_r_12 m_t_6" style="color: #737272;">
												<text>
													|
												</text>
											</view>
											<view class="">
												<view class="" v-if="item.is_stop">
													<text class="f_24_0" style="color: #737272;" v-if="item.is_yingye">
														暂停营业
													</text>
												</view>
												<view class="" v-else>
													<text class="f_24_0" style="color: #FE450C;" v-if="item.is_yingye">
														营业中
													</text>
													<text class="f_24_0" style="color: #FA7B27;" v-else>
														已打烊
													</text>
												</view>
											</view>
										</view>
									</view>
									<view class="flex" style="align-items: flex-start;">
										<view class="m_r_6 m_b_10 m_l_6"
											style="width: 28rpx; height: 28rpx;flex-shrink: 0;">
											<up-image :show-loading="true" src="/static/images/index/position_icon.png"
												width="18rpx" height="24rpx"></up-image>
										</view>
										<view class="">
											<text class="f_24_0" style="color: #737272;">
												{{item.address}}
											</text>

										</view>
									</view>
								</view>
							</view>

						</view>
						<view class="hr m_b_10">

						</view>
						<view class="row2_item_row2 flex_both">
							<view class="flex" style="align-items: flex-start;">
								<view class="m_r_10">
									<text class="f_24_0_b">
										评分
									</text>
								</view>
								<view class="m_t_6">
									<up-rate active-color="linear-gradient(to bottom, #FFFF59, #F9B900);"
										inactive-color="#b2b2b2" gutter="8" v-model="item.score" disabled></up-rate>
								</view>
							</view>
							<view class="" @click.stop="toOpenlocation(item)">
								<up-button type="primary">
									<view class="m_r_10 m_b_16">
										<up-image :show-loading="true" src="/static/images/index/index_row2_dh.png"
											width="22rpx" height="22rpx"></up-image>
									</view>
									<text class="f_24_f">
										导航
									</text>
								</up-button>
							</view>
						</view>
					</view>
				</view>
				<view class="empty_box" v-if="!loadShow &&storeList.length ==  0">
					<view class="">
						<up-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png">
						</up-empty>
					</view>
				</view>
				<view class="loading_box" v-if="loadShow">
					{{ loadMessage }}
				</view>
			</scroll-view>
		</view>
	</view>
	<up-picker ref="uCityPickerRef" :show="cityPickerShow" :columns="cityArr" keyName="name"
		@change="cityPickerChangeHandler" @cancel="cityPickerShow = false" @confirm="cityPickerConfirm"
		:defaultIndex="defaultIndex" confirmColor="#F76D11"></up-picker>
</template>
<script setup lang="ts">
	import { ref, reactive, getCurrentInstance } from "vue";
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import NavBar from "@/components/navbar.vue"
	const { proxy } = getCurrentInstance()
	const contentHeight = ref('100vh')
	const statusBarHeight = ref(88)
	const viewHeight = ref()
	onLoad((e) => {
		uni.getSystemInfo({
			success: function (info) {
				statusBarHeight.value = (info.statusBarHeight + 44) * 2
				contentHeight.value = `calc(100vh - ${statusBarHeight.value + 76 + 190 + 96}rpx)`
				viewHeight.value = `calc(100vh - ${statusBarHeight.value + 76 + 170 + 32 + 96}rpx)`
			}
		});
		console.log(e);
		longitude.value = e.longitude
		latitude.value = e.latitude
		positionInfo.value = JSON.parse(e.positionInfo)
		getNowAreaByName()
	})
	// 审核消息列表
	const page = ref(1)
	const loadShow = ref(false)
	const loadMessage = ref('加载中')
	const scrolltolowerFun = () => {
		page.value = ++page.value;
		loadShow.value = true;
		setTimeout(() => {
			getShopList()
		}, 1000)
	}

	// 区县相关
	const qqmapsdk = ref(null)
	const longitude = ref()
	const latitude = ref()
	const getNowAreaByName = async () => {
		let res = await proxy.$http("common.getNowAreaByName", { area_name: positionInfo.value.area_name, city_name: positionInfo.value.city_name })
		let data = res.data
		curAddress.value = data.province.name + '-' + data.cityInfo.name + '-' + data.areaInfo.name
		initCity(res.data)
	}
	const cityPickerShow = ref(false)
	const uCityPickerRef = ref(null)
	const rawCityData = ref([])
	const cityArr = ref([])
	const curAddress = ref('')
	const defaultIndex = ref([0, 3, 2])
	const positionInfo = ref({
		province_name: '',
		city_name: '',
		area_name: ''

	})
	const initCity = async (e) => {
		try {
			let res = await proxy.$http('common.getAreaAll')
			if (res.code === 1) {
				defaultIndex.value = []
				rawCityData.value = res.data
				positionInfo.value.province_name = e.province.name
				positionInfo.value.city_name = e.cityInfo.name
				positionInfo.value.area_name = e.areaInfo.name
				const provinceList = rawCityData.value.map(item => {
					return { name: item.name, id: item.id }
				})
				let provinceIndex = 0
				provinceList.forEach((v, index) => {
					if (v.id == e.province.id) {
						provinceIndex = index
						defaultIndex.value.push(index)
					}
				})
				const cityList = rawCityData.value[provinceIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				let cityIndex = 0
				cityList.forEach((v, index) => {
					if (v.id == e.cityInfo.id) {
						defaultIndex.value.push(index)
						cityIndex = index
					}
				})
				const counties = rawCityData.value[provinceIndex].children[cityIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				counties.forEach((v, index) => {
					if (v.id == e.areaInfo.id) {
						defaultIndex.value.push(index)
					}
				})
				console.log(defaultIndex.value);
				cityArr.value.push(provinceList, cityList, counties)
				initStore()
			} else {
				throw new Error(res.msg)
			}
		} catch (e) {
			uni.showToast({
				icon: 'none',
				title: e.message
			})
		}
	}
	const showCityPicker = () => {
		cityPickerShow.value = true
	}
	const cityPickerChangeHandler = (e) => {
		const { columnIndex, indexs } = e
		if (columnIndex === 0) {
			uCityPickerRef.value.setColumnValues(1, rawCityData.value[indexs[0]].children);
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[0].children);
		}
		if (columnIndex === 1) {
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[indexs[1]].children);
		}
	}
	const cityPickerConfirm = (e) => {
		const arr = []
		arr.push(e.value[0].name)
		arr.push(e.value[1].name)
		arr.push(e.value[2].name)
		curAddress.value = arr.join('-')
		positionInfo.value.province_name = e.value[0].name
		positionInfo.value.city_name = e.value[1].name
		positionInfo.value.area_name = e.value[2].name
		cityPickerShow.value = false
		initStore()
	}


	const storeList = ref([])
	const getShopList = async () => {
		if (loadMessage.value == '没有更多了') {
			loadShow.value = true;
			setTimeout(() => {
				loadShow.value = false;
			}, 200)
			return
		}
		let params = {
			sort_key: '',
			sort_type: ''
		}
		if (row2HeaderActiveIdx.value || row2HeaderActiveIdx.value == 0) {
			params = {
				sort_key: row2HeaderActiveIdx.value + 1,
				sort_type: row2HeaderList.value[row2HeaderActiveIdx.value].state.status == 1 ? 'asec' : 'desc'
			}
		}
		uni.showLoading({
			title:"加载中"
		})
		let res = await proxy.$http('index.getShopList', { page: page.value, lat: latitude.value, lng: longitude.value, search: searchVal.value ,...positionInfo.value})
		uni.hideLoading()
		let data = res.data.data
		if (res.code == 1) {
			if (data.length == 0) {
				loadMessage.value = "没有更多了"
			} else {
				storeList.value.push(...data)
			}
		} else {
			loadMessage.value = "加载出错"
		}
		setTimeout(() => {
			loadShow.value = false;
		}, 200)
		console.log(res);
	}
	const searchVal = ref('')
	const onSearchChage = (e) => {
		searchVal.value = e
		loadMessage.value = "加载中"
		page.value = 1
		storeList.value = []
		if (timer.value) {
			clearTimeout(timer.value)
		}
		timer.value = setTimeout(() => {
			getShopList()
		}, 200)
	}

	//
	const row2HeaderList = ref([
		{
			label: '附近',
			index: 0,
			state: {
				isSel: false,
				status: 0
			}
		},
		{

			label: '距离',
			index: 1,
			state: {
				isSel: false,
				status: 0
			}
		},
		{

			label: '销量',
			index: 2,
			state: {
				isSel: false,
				status: 0
			}
		},
		{

			label: '排行',
			index: 3,
			state: {
				isSel: false,
				status: 0
			}
		},
	])
	const row2HeaderActiveIdx = ref()
	const onClickRow2HeaderItem = (e) => {
		resetRow2Header(e)
		row2HeaderActiveIdx.value = e.index
		switch (e.state.status) {
			case 0:
				row2HeaderList.value[e.index].state.isSel = true;
				row2HeaderList.value[e.index].state.status = 1;
				break;
			case 1:
				row2HeaderList.value[e.index].state.isSel = true;
				row2HeaderList.value[e.index].state.status = 2;
				break;
			case 2:
				row2HeaderList.value[e.index].state.isSel = false;
				row2HeaderList.value[e.index].state.status = 0;
				break;
		}
		initStore()
	}
	const resetRow2Header = (e) => {
		row2HeaderList.value.forEach((v, index) => {
			if (index != e.index) {
				v.state.isSel = false;
				v.state.status = 0;
			}
		})

	}
	const timer = ref(null)
	const initStore = () => {
		page.value = 1
		loadMessage.value = '加载中'
		storeList.value = []
		if (timer.value) {
			clearTimeout(timer.value)
		}
			getShopList()
	}
	const toDetail = (e) => {
		uni.navigateTo({
			url: `/pages/index/storeDetail?id=${e.shop_id}`
		})
	}
	const toOpenlocation = (e) => {
		if (!e.lat || e.lng) {
			uni.$u.toast('坐标缺失')
			return
		}
		uni.openLocation({
			// 目标位置的经纬度
			latitude: parseFloat(e.lat),
			longitude: parseFloat(e.lng),
			// 目标位置的名称
			name: e.shop_name,
			// 目标位置的详细地址
			address: e.address,
			// 地图缩放比例
			scale: 18,
			// 调用成功时的回调函数
			success: function (res) {
				console.log('调用成功：', res)
			},
			// 调用失败时的回调函数
			fail: function (res) {
				console.log('调用失败：', res)
			},
			// 调用完成时的回调函数
			complete: function (res) {
				console.log('调用完成：', res)
			}
		})
	}
</script>
<style lang="scss" scoped>
	.nav_box {
		.nav_main {
			display: flex;
			align-items: center;
		}
	}

	.search_box {
		width: 750rpx;
		background: #F7F8FC;
		position: fixed;
		z-index: 9;

		.search_input {
			padding: 11rpx 0;
			margin-left: 20rpx;
			background: #FFFFFF;
			box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
			border-radius: 34rpx;
			position: relative;


			.search_icon {
				position: absolute;
				left: 260rpx;
				top: 16rpx;
			}
		}

		.row2_header {
			background: #F7F8FC;
			padding: 0 20rpx;

			.row2_header_list {

				.row2_header_item {
					width: 167rpx;
					height: 59rpx;
					background: #FFFFFF;
					border-radius: 10rpx;
				}

				.row2_header_item {
					width: 167rpx;
					height: 59rpx;
					background: #E5E2E2;
					border-radius: 10rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					.text {
						font-size: 30rpx;
						color: #000000;
					}
				}

				.row2_header_item_acitve {
					background: #FD9125 !important;

					.text {
						color: white !important;
					}

					.active_box {
						width: 24rpx;
						height: 24rpx;
						background: #EFF0F4;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
					}

				}
			}
		}

	}




	.content {
		background: #F7F8FC;
		padding: 20rpx;
		padding-bottom: 64rpx;



		.row2_list {
			.row2_item {
				padding: 20rpx;
				width: 672rpx;
				background: #FFFFFF;
				box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
				border-radius: 10rpx;

				::v-deep.row2_item_row2 .u-button {
					width: 143rpx;
					height: 47rpx;
					background: linear-gradient(90deg, #F7A52F, #F97119);
					border-radius: 24rpx;
					border: 0;
				}
			}
		}

	}
</style>